package cn.yangliu.nacos.oauth2.config;

import cn.yangliu.nacos.comm.handler.ResultConverter;
import cn.yangliu.nacos.oauth2.ex.OAuthException;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.stereotype.Component;

/**
 * The type of nacos.
 *
 * @author 问道于盲
 * @date 2020 -01-05
 */
@Component
public class Oauth2ResultConverter implements ResultConverter {

    /**
     * Convert object.
     *
     * @param result             the result
     * @param serverHttpRequest  the server http request
     * @param serverHttpResponse the server http response
     * @return the object
     */
    @Override
    public Object convert(Object result, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
       if (result instanceof OAuthException) {
           OAuthException exception = (OAuthException) result;
           if (exception.getCause() instanceof InvalidGrantException) {
               serverHttpResponse.setStatusCode(HttpStatus.UNAUTHORIZED);
           }
           return result;
       }
        return null;
    }
}
